<template>
  <div>
    <el-cascader
      v-model="selectedValue"
      :options="cascaderOptions"
      :props="cascaderProps"
      placeholder="请选择"
      @change="handleChange"
    />
  </div>
</template>

<script>
import { selectAllSysDept, selectAllSysDeptByID } from "@/api/purchase/purchase";
import {findParent, findSelect} from "@/api/product/type";

export default {
  data() {
    return {
      selectedValue: [],
      cascaderOptions: [],
      cascaderProps: {
        value: undefined,
        label: undefined,
        children: undefined,
        checkStrictly: true // 允许非叶子节点的选项被选择
      }
    };
  },
  created() {
    this.fetchItems();
  },
  methods: {
    async fetchItems() {
      try {
        const response = await selectAllSysDept();
        console.log('Response from findSelect:', response);
        if (Array.isArray(response)) {
          this.cascaderOptions = await this.convertToCascaderOptions(response);
          console.log('Converted cascaderOptions:', this.cascaderOptions);
        } else {
          console.error('Expected an array, but got:', response);
        }
      } catch (error) {
        console.error('Error fetching items:', error);
      }
    },
    async convertToCascaderOptions(data) {
      if (!Array.isArray(data)) {
        console.error('Expected an array, but got:', data);
        return [];
      }

      // 创建一个映射，用于快速查找父项
      const itemMap = new Map(data.map(item => [item.deptId, item]));
      // 创建一个数组，用于存储顶级项
      const topLevelItems = [];

      data.forEach(async (item) => {
        if (item.parentId === 0) {
          // 顶级项直接添加到 topLevelItems
          topLevelItems.push(await this.createOption(item));
        } else {
          // 非顶级项，尝试找到其父项并添加到 children 数组
          const parentItem = itemMap.get(item.parentId);
          if (parentItem) {
            const childItem = await this.createOption(item);
            if (parentItem.children) {
              parentItem.children.push(childItem);
            } else {
              parentItem.children = [childItem];
            }
          }
        }
      });

      return topLevelItems;
    },
    async createOption(item) {
      return {
        value: item.deptId,
        label: item.deptName,
        children: await this.fetchChildren(item.deptId)
      };
    },
    async fetchChildren(parentId) {
      try {
        const response = await selectAllSysDeptByID(parentId);
        console.log('Response from findParent:', response);
        if (Array.isArray(response)) {
          return Promise.all(response.map(async (item) => {
            return {
              value: item.deptId,
              label: item.deptName,
              children: await this.fetchChildren(item.deptId)
            };
          }));
        } else {
          console.error('Expected an array, but got:', response);
          return [];
        }
      } catch (error) {
        console.error('Error fetching children:', error);
        return [];
      }
    },
    handleChange(value) {
      console.log('Selected:', value);
      const currentSelectedValue = value[value.length - 1];
      console.log('Current Selected:', currentSelectedValue);
      alert(currentSelectedValue);
      //this.form.parentId=currentSelectedValue;
    }
  }
};
</script>

<style scoped>
/* 确保没有样式冲突 */
.el-cascader {
  display: block;
  width: 100%;
  padding: 8px;
  margin-top: 5px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}
</style>
